package com.xy.webadmin.app.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.github.pagehelper.page.PageMethod;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.xy.common.core.annotation.MyRequestBody;
import com.xy.common.core.constant.ErrorCodeEnum;
import com.xy.common.core.object.*;
import com.xy.common.core.util.MyCommonUtil;
import com.xy.common.core.util.MyModelUtil;
import com.xy.common.core.util.MyPageUtil;
import com.xy.common.log.annotation.OperationLog;
import com.xy.common.log.model.constant.SysOperationLogType;
import com.xy.webadmin.app.dto.MqttBrokerConfigDto;
import com.xy.webadmin.app.model.MqttBrokerConfig;
import com.xy.webadmin.app.service.MqttBrokerConfigService;
import com.xy.webadmin.app.vo.MqttBrokerConfigVo;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * MQTT终端配置操作控制器类。
 *
 * @author xiaoyue
 * @date 2025-05-13
 */
@Tag(name = "MQTT终端配置管理接口")
@Slf4j
@RestController
@RequestMapping("/admin/app/mqttBrokerConfig")
public class MqttBrokerConfigController {

    @Autowired
    private MqttBrokerConfigService mqttBrokerConfigService;

    /**
     * 新增MQTT终端配置数据。
     *
     * @param mqttBrokerConfigDto 新增对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {"mqttBrokerConfigDto.id"})
    @SaCheckPermission("mqttBrokerConfig.add")
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Long> add(@MyRequestBody MqttBrokerConfigDto mqttBrokerConfigDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(mqttBrokerConfigDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        MqttBrokerConfig mqttBrokerConfig = MyModelUtil.copyTo(mqttBrokerConfigDto, MqttBrokerConfig.class);
        // 验证关联Id的数据合法性
        CallResult callResult = mqttBrokerConfigService.verifyRelatedData(mqttBrokerConfig, null);
        if (!callResult.isSuccess()) {
            return ResponseResult.errorFrom(callResult);
        }
        mqttBrokerConfig = mqttBrokerConfigService.saveNew(mqttBrokerConfig);
        return ResponseResult.success(mqttBrokerConfig.getId());
    }

    /**
     * 更新MQTT终端配置数据。
     *
     * @param mqttBrokerConfigDto 更新对象。
     * @return 应答结果对象。
     */
    @SaCheckPermission("mqttBrokerConfig.update")
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    public ResponseResult<Void> update(@MyRequestBody MqttBrokerConfigDto mqttBrokerConfigDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(mqttBrokerConfigDto, true);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        MqttBrokerConfig mqttBrokerConfig = MyModelUtil.copyTo(mqttBrokerConfigDto, MqttBrokerConfig.class);
        MqttBrokerConfig originalMqttBrokerConfig = mqttBrokerConfigService.getById(mqttBrokerConfig.getId());
        if (originalMqttBrokerConfig == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [数据] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        // 验证关联Id的数据合法性
        CallResult callResult = mqttBrokerConfigService.verifyRelatedData(mqttBrokerConfig, originalMqttBrokerConfig);
        if (!callResult.isSuccess()) {
            return ResponseResult.errorFrom(callResult);
        }
        if (!mqttBrokerConfigService.update(mqttBrokerConfig, originalMqttBrokerConfig)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success();
    }

    /**
     * 删除MQTT终端配置数据。
     *
     * @param id 删除对象主键Id。
     * @return 应答结果对象。
     */
    @SaCheckPermission("mqttBrokerConfig.delete")
    @OperationLog(type = SysOperationLogType.DELETE)
    @PostMapping("/delete")
    public ResponseResult<Void> delete(@MyRequestBody Long id) {
        if (MyCommonUtil.existBlankArgument(id)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        return this.doDelete(id);
    }

    /**
     * 批量删除MQTT终端配置数据。
     *
     * @param idList 待删除对象的主键Id列表。
     * @return 应答结果对象。
     */
    @SaCheckPermission("mqttBrokerConfig.delete")
    @OperationLog(type = SysOperationLogType.DELETE_BATCH)
    @PostMapping("/deleteBatch")
    public ResponseResult<Void> deleteBatch(@MyRequestBody List<Long> idList) {
        if (MyCommonUtil.existBlankArgument(idList)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        for (Long id : idList) {
            ResponseResult<Void> responseResult = this.doDelete(id);
            if (!responseResult.isSuccess()) {
                return responseResult;
            }
        }
        return ResponseResult.success();
    }

    /**
     * 列出符合过滤条件的MQTT终端配置列表。
     *
     * @param mqttBrokerConfigDtoFilter 过滤对象。
     * @param orderParam 排序参数。
     * @param pageParam 分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @SaCheckPermission("mqttBrokerConfig.view")
    @PostMapping("/list")
    public ResponseResult<MyPageData<MqttBrokerConfigVo>> list(
            @MyRequestBody MqttBrokerConfigDto mqttBrokerConfigDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize(), pageParam.getCount());
        }
        MqttBrokerConfig mqttBrokerConfigFilter = MyModelUtil.copyTo(mqttBrokerConfigDtoFilter, MqttBrokerConfig.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, MqttBrokerConfig.class);
        List<MqttBrokerConfig> mqttBrokerConfigList =
                mqttBrokerConfigService.getMqttBrokerConfigListWithRelation(mqttBrokerConfigFilter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(mqttBrokerConfigList, MqttBrokerConfigVo.class));
    }

    /**
     * 查看指定MQTT终端配置对象详情。
     *
     * @param id 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @SaCheckPermission("mqttBrokerConfig.view")
    @GetMapping("/view")
    public ResponseResult<MqttBrokerConfigVo> view(@RequestParam Long id) {
        MqttBrokerConfig mqttBrokerConfig = mqttBrokerConfigService.getByIdWithRelation(id, MyRelationParam.full());
        if (mqttBrokerConfig == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        MqttBrokerConfigVo mqttBrokerConfigVo = MyModelUtil.copyTo(mqttBrokerConfig, MqttBrokerConfigVo.class);
        return ResponseResult.success(mqttBrokerConfigVo);
    }

    private ResponseResult<Void> doDelete(Long id) {
        String errorMessage;
        // 验证关联Id的数据合法性
        MqttBrokerConfig originalMqttBrokerConfig = mqttBrokerConfigService.getById(id);
        if (originalMqttBrokerConfig == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [对象] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (!mqttBrokerConfigService.remove(id)) {
            errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success();
    }
}
